package com.example.onlinemusicserver.controller;

import com.example.onlinemusicserver.mapper.LoveMusicMapper;
import com.example.onlinemusicserver.mapper.MusicMapper;
import com.example.onlinemusicserver.model.Music;
import com.example.onlinemusicserver.model.User;
import com.example.onlinemusicserver.service.MusicService;
import com.example.onlinemusicserver.tools.Constant;
import com.example.onlinemusicserver.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/music")
public class MusicController {
    @Value("${music.local.path}")
    public  String SAVE_PATH;

    @Autowired
   private MusicService musicService;

    @Autowired
   private MusicMapper musicMapper;

    @Autowired
    private LoveMusicMapper loveMusicMapper;



    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename")MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse response)throws IOException{

        // 1.检查是否登录了
        HttpSession session=request.getSession(false);
        if (session==null || session.getAttribute(Constant.USERINFO_SESSION_KEY) ==null){
            System.out.println("用户未登录");
            return new ResponseBodyMessage<>(-1,"请登录后上传",false);
        }

        // 还要判断一下当前数据库中是否有同一首歌曲
        // 判断依据是歌曲名+歌手

        String fileNameAndType=file.getOriginalFilename(); // xxx.mp3
        int index=fileNameAndType.lastIndexOf(".");
        String title=fileNameAndType.substring(0,index);

        Music music=musicService.selectByTAndSinger(title,singer);
        if (music!=null){
            return new ResponseBodyMessage<>(-1,"上传失败！当前数据库已有这首歌曲",false);
        }





        System.out.println("fileNameAndType:"+fileNameAndType);
        String path=SAVE_PATH+fileNameAndType;
        System.out.println(path);
        File dest=new File(path);
        if (!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);
            // return new ResponseBodyMessage<>(0,"上传成功",true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1,"上传失败",false);
        }

        // 进行数据库的上传
        //1. 准备数据
        //2. 调用insert

        User user=(User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid= user.getId();

        // 1. 播放音乐 （http请求）
        String url="/music/get?path="+title;

        // 当前时间
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String time=simpleDateFormat.format(new Date());



        try {
            int ret=musicService.insert(title,singer,time,url,userid);
            if (ret==1){
                // 数据库上传成功
                // 应该跳转到音乐列表页面
                response.sendRedirect("/list.html");

                return new ResponseBodyMessage<>(0,"上传成功",true);
            }else {
                return new ResponseBodyMessage<>(-1,"上传失败",false);
            }
        }catch(Exception e){
            dest.delete();
            return new ResponseBodyMessage<>(-1,"上传失败",false);

        }
    }

    /**
     * 播放音乐接口
     * /music/get?path==xxx.mp3
     * @param path
     * @return
     */

    @RequestMapping("/get")
    public ResponseEntity<byte[]> func(String path){
        File file=new File(SAVE_PATH+path);
        byte[] a=null;
        try {
           a= Files.readAllBytes(file.toPath());
           if (a==null){
               return  ResponseEntity.badRequest().build();
           }
           return ResponseEntity.ok(a);
        }catch (IOException e){
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除音乐根据id
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id){
        // 1.先检查这个英语是否存在
        int iid=Integer.parseInt(id);
        Music music=musicMapper.findMusicById(iid);
        if (music==null){
            System.out.println("没有这个id的音乐");
            return new ResponseBodyMessage<>(-1,"要删除的音乐不存在",false);
        }else {
            // 2.删除数据库和服务器的音乐
            // 2.删除数据库
            int ret=musicMapper.deleteMusicById(iid);
            if (ret==1){
                // 数据库删除成功 接着删除服务器上的音乐
                int index=music.getUrl().lastIndexOf("=");
                String fileName=music.getUrl().substring(index+1);
                File file=new File(SAVE_PATH+fileName+".mp3");
                System.out.println("当前文件路径是："+file.getPath());
                if (file.delete()){
                    loveMusicMapper.deleteLoveMusicById(iid);
                    return new ResponseBodyMessage<>(0,"服务器以及数据库当中音乐均删除成功!",true);
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器当中音乐删除失败",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库当中音乐没有删除成功",false);
            }
        }
    }

    /**
     * 批量删除音乐
     * @param ids
     * @return
     */
    @RequestMapping("/deletesel")
    public ResponseBodyMessage<Boolean> deleteSelMusic(@RequestParam("id[]")List<Integer> ids){
        System.out.println("所有的id为："+ids);
        int sum=0;
        for (int i = 0; i < ids.size(); i++) {
            int musicId=ids.get(i);
            Music music=musicMapper.findMusicById(musicId);
            if (music==null){
                System.out.println("没有这个id的音乐");
                return new ResponseBodyMessage<>(-1,"要删除的音乐不存在",false);
            }
            int ret=musicMapper.deleteMusicById(musicId);
            if (ret==1){
                // 数据库删除成功 接着删除服务器上的音乐
                int index=music.getUrl().lastIndexOf("=");
                String fileName=music.getUrl().substring(index+1);
                File file=new File(SAVE_PATH+fileName+".mp3");
                System.out.println("当前文件路径是："+file.getPath());
                if (file.delete()){
                    loveMusicMapper.deleteLoveMusicById(musicId);
                    sum+=ret;
                }else {
                    return new ResponseBodyMessage<>(-1,"服务器当前音乐删除失败！",false);
                }
            }else {
                return new ResponseBodyMessage<>(-1,"数据库当前音乐删除失败！",false);
            }
        }
        if (sum==ids.size()){
            System.out.println("整体删除成功");
            return new ResponseBodyMessage<>(0,"选中音乐均删除成功！",true);
        }else {
            System.out.println("整体删除失败");
            return new ResponseBodyMessage<>(-1,"选中音乐未能均删除成功！",false);
        }
    }

    // 根据音乐名称查询音乐 支持模糊查询
    // 要是没传音乐名字 默认查询全部音乐
    @RequestMapping("findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        List<Music> musicList=null;
        if (musicName!=null){
            musicList=musicMapper.findMusicByName(musicName);
        }else {
            musicList=musicMapper.findMusicAll();
        }
        return new ResponseBodyMessage<>(0,"查询音乐成功,查询到的音乐数量是:"+musicList.size(),musicList);
    }

}
